package com.key.win.system.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.key.win.system.model.SysOrgan;
import com.key.win.system.model.SysOrganUser;
import com.key.win.system.model.SysUser;
import com.key.win.system.model.SysUserOrgan;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Set;


/**
 * 用户机构关系
 */
@Mapper
public interface SysUserOrganDao extends BaseMapper<SysOrganUser> {

    int deleteUserOrgan(@Param("userId") String userId, @Param("organId") String organId);

    /**
     * 根据用户id获取Organ
     *
     * @param userId
     * @return
     */
    @Select("select o.* from sys_user_organ uo inner join sys_organ o on uo.organ_id = o.id where uo.user_id = #{userId} and uo.enable_flag = 1 and o.enable_flag = 1")
    List<SysOrgan> findOrganByUserId(String userId);

    /**
     * 根据用户id获取Organ
     *
     * @param organId
     * @return
     */
    @Select("select u.* from sys_user_organ uo inner join sys_user u on uo.user_id = u.id where uo.organ_id = #{organId} and uo.enable_flag = 1 and u.enable_flag = 1")
    List<SysUser> findUserByOrganId(String organId);

    /**
     * 根据用户ids 获取
     *
     * @param userIds
     * @return
     */

    @Select("<script>select r.* from sys_user_organ uo inner join sys_organ r on r.id = ru.organ_id where  ru.enable_Flag = 1 and uo.enable_Flag = 1 and ru.user_id IN " +
            " <foreach item='item' index='index' collection='list' open='(' separator=',' close=')'> " +
            " #{item} " +
            " </foreach>" +
            "</script>")
    List<SysOrgan> findOrganByUserIds(List<String> userIds);

    /**
     * 根据用户ids 获取
     *
     * @param organIds
     * @return
     */

    @Select("<script>select u.* from sys_user_organ uo inner join sys_user u on u.id = uo.user_id where u.enable_Flag = 1 and uo.enable_Flag = 1  and ru.organ_id IN " +
            " <foreach item='item' index='index' collection='list' open='(' separator=',' close=')'> " +
            " #{item} " +
            " </foreach>" +
            "</script>")
    List<SysUser> findUserByOrganIds(List<String> organIds);

    void saveBatchUserIdAndOrganIds(@Param("userId") String userId, @Param("organIds") Set<String> organIds);

    void saveBatchUserIdsAndOrganId(@Param("userIds") Set<String> userIds, @Param("organId") String organId);

    /**
     * 根据用户id获取组信息
     *
     * @param organId
     * @return
     */
    @Select("select u.* from sys_user_organ gu inner join sys_user g on g.id = gu.user_id where gu.organ_id = #{organId} and g.enable_flag = 1 and gu.enable_flag = 1")
    List<SysUser> findUserPagedByOrganId(IPage<SysUser> page, String organId);

}
